<script type="text/javascript">
    $(document).ready(function() {
        $('.scroll-pane').jScrollPane();
        $('.scroll-pane-arrows').jScrollPane(
            {
                showArrows: true,
                horizontalGutter: 10
            }
        );
        $('.scroll-pane-arrows-big-grid').jScrollPane(
            {
                showArrows: true,
                horizontalGutter: 10
            }
        );

        $("#warning_modal").dialog(
        {
            autoOpen: false,
            modal: true,
            width: 500,
            heigth: 'auto',
            buttons:{
                Ok: function() {
                    $(this).dialog("close");
                },
            }
        });

        function errorFormBLine()
        {
            var error = '';
            var valor = '';
            
            valor = document.getElementById('nameBL').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Name field is required";

            if(valor.length > 250)
              return "The Name field can not contain more than 250 characters";

            indice = document.getElementById("idRoundBL").selectedIndex;
            if(indice == null) {
              return "The Round field is required";
            }

            return error;
        }

        // Pop up Business line
        $("#add_b_line").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              buttons:{
                Save: function() {
                    // Validar que el formulario esté completo antes de continuar
                    var validationError = errorFormBLine();
                    if(validationError == '') { // Campos obligatorios completos
                        // Tengo que hacer una validación más, que corresponde a que
                        // el nombre del item no puede estar duplicado
                        var nameItem = document.getElementById('nameBL').value;
                        var idParent = document.getElementById("idRoundBL").options[document.getElementById("idRoundBL").selectedIndex].value;
                        $.ajax({
                             type: 'POST',
                             //Realizaremos la petición al metodo validUsername del controlador User
                             url: '<?php echo site_url(); ?>bline/existName',
                             dataType: 'text',
                             data:  "item="+nameItem+"&idParent="+idParent,
                             success: function(resp) {
                                if(resp != '1') add_form_bl.submit();
                                else document.getElementById('bline_form_msg').innerHTML = 'This Business Line name already exists';
                             }
                         });
                    }
                    else {
                        document.getElementById('bline_form_msg').innerHTML = validationError;
                    }
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });

        function errorFormOutcome()
        {
            var error = '';
            var valor = '';
            
            valor = document.getElementById('nameOC').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Name field is required";

            if(valor.length > 250)
              return "The Name field can not contain more than 250 characters";

            indice = document.getElementById("blineoc").selectedIndex;
            if(indice == null) {
              return "The Business Line field is required";
            }

            return error;
        }

        // Pop up outcome
        $("#add_outcome").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              buttons:{
                Save: function() {
                    // Validar que el formulario esté completo antes de continuar
                    var validationError = errorFormOutcome();
                    if(validationError == '') {
                        // Tengo que hacer una validación más, que corresponde a que
                        // el nombre del item no puede estar duplicado
                        var nameItem = document.getElementById('nameOC').value;
                        var idParent = document.getElementById("blineoc").options[document.getElementById("blineoc").selectedIndex].value;
                        $.ajax({
                             type: 'POST',
                             //Realizaremos la petición al metodo validUsername del controlador User
                             url: '<?php echo site_url(); ?>outcome/existName',
                             dataType: 'text',
                             data:  "item="+nameItem+"&idParent="+idParent,
                             success: function(resp) {
                                if(resp != '1') add_form_oc.submit();
                                else document.getElementById('outcome_form_msg').innerHTML = 'This Outcome name already exists';
                             }
                         });
                    }
                    else {
                        document.getElementById('outcome_form_msg').innerHTML = validationError;
                    }
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });


        function errorFormOutput()
        {
            var error = '';
            var valor = '';
            
            valor = document.getElementById('nameOP').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Name field is required";

            if(valor.length > 250)
              return "The Name field can not contain more than 250 characters";

            indice = document.getElementById("outcome_op").selectedIndex;
            if(indice == null) {
              return "The Outcome field is required";
            }

            return error;
        }

        // Pop up output
        $("#add_output").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              buttons:{
                Save: function() {
                    // Validar que el formulario esté completo antes de continuar
                    var validationError = errorFormOutput();
                    if(validationError == '') {
                        // Tengo que hacer una validación más, que corresponde a que
                        // el nombre del item no puede estar duplicado
                        var nameItem = document.getElementById('nameOP').value;
                        var idParent = document.getElementById("outcome_op").options[document.getElementById("outcome_op").selectedIndex].value;
                        $.ajax({
                             type: 'POST',
                             //Realizaremos la petición al metodo validUsername del controlador User
                             url: '<?php echo site_url(); ?>output/existName',
                             dataType: 'text',
                             data:  "item="+nameItem+"&idParent="+idParent,
                             success: function(resp) {
                                if(resp != '1') add_form_op.submit();
                                else document.getElementById('output_form_msg').innerHTML = 'This Output name already exists';
                             }
                         });
                    }
                    else {
                        document.getElementById('output_form_msg').innerHTML = validationError;
                    }
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });

        function errorFormIndicator()
        {
            var error = '';
            var valor = '';
            
            valor = document.getElementById('nameInd').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Name field is required";

            if(valor.length > 250)
              return "The Name field can not contain more than 250 characters";
            
            indice = document.getElementById("output_ind").selectedIndex;
            if(indice == null) {
              return "The Output field is required";
            }

            return error;
        }

        // Pop up indicator
        $("#add_indicator").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              buttons:{
                Save: function() {
                    // Validar que el formulario esté completo antes de continuar
                    var validationError = errorFormIndicator();
                    if(validationError == '') {
                        // Tengo que hacer una validación más, que corresponde a que
                        // el nombre del item no puede estar duplicado
                        var nameItem = document.getElementById('nameInd').value;
                        var idParent = document.getElementById("output_ind").options[document.getElementById("output_ind").selectedIndex].value;
                        $.ajax({
                             type: 'POST',
                             //Realizaremos la petición al metodo validUsername del controlador User
                             url: '<?php echo site_url(); ?>indicator/existName',
                             dataType: 'text',
                             data:  "item="+nameItem+"&idParent="+idParent,
                             success: function(resp) {
                                if(resp != '1') add_form_ind.submit();
                                else document.getElementById('ind_form_msg').innerHTML = 'This Indicator name already exists';
                             }
                         });
                    }
                    else {
                        document.getElementById('ind_form_msg').innerHTML = validationError;
                    }
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });
    });

    function showNewItemModal(item, idParent, idItemEdit)
    {
        var url_datos = '';
        var selector = '';

        switch (item) {
            case 'bl':
                if(idItemEdit == 0) url_datos = 'bline/addBusinessLine';
                else url_datos = 'bline/editBusinessLine/'+idItemEdit;

                selector = '#add_b_line';
                break;
            case 'oc':
                if(idItemEdit == 0) url_datos = 'outcome/addoutcome/'+idParent;
                else url_datos = 'outcome/editOutcome/'+idItemEdit+'/'+idParent;

                selector = '#add_outcome';
                break;
            case 'op':
                if(idItemEdit == 0) url_datos = 'output/addOutput/'+idParent;
                else url_datos = 'output/editOutput/'+idItemEdit+'/'+idParent;

                selector = '#add_output';          
                break;
            case 'in':
                if(idItemEdit == 0) url_datos = 'indicator/addindicator/'+idParent;
                else url_datos = 'indicator/editIndicator/'+idItemEdit+'/'+idParent;

                selector = '#add_indicator';           
                break;         
        }

        url_datos = '<?php echo site_url(); ?>'+url_datos;
        $.ajax({
             type: 'POST',
             //Realizaremos la petición al metodo addUser del controlador User
             url: url_datos,
             
             //Cuando se procese con éxito la petición se ejecutará esta función
             success: function(resp) {
                $(selector).dialog("open").html(resp);
             }
         });
    }

    function deleteItem(item, idItem, idItem2, idItem3, idItem4)
    {
        var url_eliminar = '';
        var url_consulta = '';
        var selector = '#warning_modal';
        var textMsg = '';

        switch (item) {
            case 'bl':
                url_eliminar = '<?php echo site_url(); ?>bline/deletebusinessline/'+idItem;
                url_consulta = '<?php echo site_url(); ?>bline/permittedDelete';
                textMsg = 'Can not delete a Business Line with associated Outcomes.';
                break;
            case 'oc':
                url_eliminar = '<?php echo site_url(); ?>outcome/deleteoutcome/'+idItem+'/'+idItem2;
                url_consulta = '<?php echo site_url(); ?>outcome/permittedDelete';
                textMsg = 'Can not delete an Outcome with associated Outputs.';
                break;
            case 'op':
                url_eliminar = '<?php echo site_url(); ?>output/deleteoutput/'+idItem+'/'+idItem2+'/'+idItem3;
                url_consulta = '<?php echo site_url(); ?>output/permittedDelete';
                textMsg = 'Can not delete an Output with associated Indicators.';
                break;
            case 'ind':
                url_eliminar = '<?php echo site_url(); ?>indicator/deleteindicator/'+idItem+'/'+idItem2+'/'+idItem3+'/'+idItem4;
                url_consulta = '<?php echo site_url(); ?>indicator/permittedDelete';
                textMsg = 'Can not delete an Indicator with associated round inputs.';
                break;
        }

        $.ajax({
             type: 'POST',
             //Realizaremos la consulta para saber si el elemento pued eliminarse
             url: url_consulta,
             dataType: 'text',
             data: 'item='+idItem,
             //Cuando se procese con éxito la petición se ejecutará esta función
             success: function(resp) {
                if(resp == '1') // Se puede eliminar el elemento
                {
                  document.location.href = url_eliminar;
                }
                else {
                    $("#warning_msg").text(textMsg);
                    $(selector).dialog("open");
                }
             }
         });
    }
</script>

<table width="100%">
	<tr>
    	<td class="menuActual">Config > Data</td>
    </tr>
    <tr>
    	<td align="center">
        	<table width="1%">
            	<tr>
                	<td>
                    	<table class="contenedora" cellpadding="0" cellspacing="0">
                        	<tr>
                            	<td class="descripcion">Bussines Line</td>
                              <td class="delete">Edit</td>
                              <td class="delete">Delete</td>
                            </tr>
                            <tr>
                            	<td colspan="3">
                                <div class="scroll-pane-arrows"> <!-- Tabla con el contenido de Business Lines -->
                                	<table width="100%" id="tblBussinesLines" class="tablaJerarquia">
                                    	<tbody>
										                <?php
                                        if (count($business_lines) > 0) {
                                            foreach($business_lines as $bline) { ?>
                                            <tr <?php if($bline->id == $idBusinessLine) echo "class='row_selected'"; ?>>
                                              <?php $url = site_url('information/getAll/' . $bline->id); ?>
                                                <td class="tdDescripcion">
                                                  <a style="Cursor:pointer" onclick="abrir_vinculo('<?=$url?>')"><?php echo $bline->name; ?> </a>
                                                </td>
                                                <td><a onclick="showNewItemModal('bl', 0, <?=$bline->id?>)" href="#">Edit</a></td>
                                                <td><a onclick="deleteItem('bl', <?=$bline->id?>, 0, 0, 0)" href="#">Delete</a></td>
                                            </tr>
                                        <?php }
                                        } else { echo 'No information'; }?>
                                        </tbody>
                                    </table>
                                </div>  <!-- Fin Contenido de Business Lines -->
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" class="footer">
                                    <input onclick="showNewItemModal('bl', 0, 0)" value="Add Business Line" type="button" class="footer_button" />
                                </td>
                            </tr>
                        </table>
                    </td>
                    <td class="separadorGrilas"></td>
                    <td>
                    	<table class="contenedora" cellpadding="0" cellspacing="0">
                        	<tr>
                            	<td class="descripcion">Outcome</td>
                            	<td class="delete">Edit</td>
                              <td class="delete">Delete</td>
                            </tr>
                            <tr>
                            	<td colspan="3">
                                <div class="scroll-pane-arrows"> <!-- Tabla con el contenido de Outcome -->
                                    <table width="100%" id="tblOutcome" class="tablaJerarquia">
                                        <tbody>
										                  <?php
                                        if (count($outcomes) > 0) {
                                            foreach($outcomes as $outcome) { ?>
                                            <tr <?php if($outcome->id == $idOutcome) echo "class='row_selected'"; ?>>
                                                <td class="tdDescripcion">
                                                  <a style="Cursor:pointer" onclick="abrir_vinculo('<?php 
													$url = 'information/getAll/' . $idBusinessLine . '/' . $outcome->id;
													echo site_url("$url");?>')"> <?php echo $outcome->name; ?></a>
                                                </td>
                                                <td><a onclick="showNewItemModal('oc', <?=$idBusinessLine?>, <?=$outcome->id?>)" href="#">Edit</a></td>
                                                <td><a onclick="deleteItem('oc', <?=$outcome->id?>, <?=$idBusinessLine?>, 0, 0)" href="#">Delete</a></td>
                                            </tr>
                                        <?php }
                                        } else { echo 'No information'; }?>
                                        </tbody>
                                    </table>
                                </div> <!-- FIN Tabla con el contenido de Business Lines -->
                                </td>
                            </tr>
                            <tr>
                            	<td colspan="3" class="footer">
                                	<input onclick="showNewItemModal('oc', <?=$idBusinessLine?>, 0)" value="Add Outcome" type="button" class="footer_button" />
                                </td>
                            </tr>
						</table>
					</td>
				</tr>
                <tr>
                    <td class="separadorMenu">
                        <table class="contenedora" cellpadding="0" cellspacing="0">
                            <tr>
                                <td class="descripcion">Output</td>
                                <td class="delete">Edit</td>
                                <td class="delete">Delete</td>
                            </tr>
                            <tr>
                                <td colspan="3">
                                    <div class="scroll-pane-arrows"> <!-- Tabla con el contenido de Output -->
                                        <table width="100%" id="tblOutput" class="tablaJerarquia">
                                            <tbody>
											                     <?php
                                            if (count($outputs) > 0) {
                                                foreach($outputs as $output) { ?>
                                                <tr <?php if($output->id == $idOutput) echo "class='row_selected'"; ?>>
                                                  <td class="tdDescripcion">
                                                    <a style="Cursor:pointer" onclick="abrir_vinculo('<?php 
                                                        $url = 'information/getAll/'. $idBusinessLine . '/' . $idOutcome . '/' . $output->id;
                                                        echo site_url("$url"); ?>')"> <?php echo $output->name; ?></a></td>
                                                  <td><a onclick="showNewItemModal('op', <?=$idOutcome?>, <?=$output->id?>)" href="#">Edit</a></td>
                                                  <td><a onclick="deleteItem('op', <?=$output->id?>, <?=$idBusinessLine?>, <?=$idOutcome?>, 0)" href="#">Delete</a></td>
                                                </tr>
                                            <?php }
											                     } else { echo 'No information'; }?>
                                            </tbody>
                                        </table>
                                    </div> <!-- FIN Tabla con el contenido de Business Lines -->
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" class="footer">
                                	<input onclick="showNewItemModal('op', <?=$idOutcome?>, 0)" value="Add Output" type="button" class="footer_button" />
                                </td>
                            </tr>
                        </table>
                    </td>
                    <td class="separadorGrilas"></td>
                    <td class="separadorMenu">
                        <table class="contenedora" cellpadding="0" cellspacing="0">
                            <tr>
                                <td class="descripcion">Indicator</td>
                                <td class="delete">Edit</td>
                                <td class="delete">Delete</td>
                            </tr>
                            <tr>
                                <td colspan="3">
                                    <div class="scroll-pane-arrows"> <!-- Tabla con el contenido de Indicators -->
                                        <table width="100%" id="tblIndicator" class="tablaJerarquia">
                                            <tbody>
											                     <?php
                                            if (count($indicators) > 0) {
                                                $idOwner = 0;
                                                foreach($indicators as $indicator) { ?>
                                                <tr <?php 
                                                if($indicator->id == $idIndicator) { 
                                                    echo "class='row_selected'";
                                                    $idOwner = $indicator->idOwner;
                                                } ?>>
                                                    <td class="tdDescripcion">
                                                      <a style="Cursor:pointer" onclick="abrir_vinculo('<?php 
                                                        $url = 'information/getAll/'. $idBusinessLine . '/' . $idOutcome . '/' . $idOutput . '/' . $indicator->id;
                                                        echo site_url("$url"); ?>')"><?php echo $indicator->name; ?></a></td>
                                                  <td><a onclick="showNewItemModal('in', <?=$idOutput?>, <?=$indicator->id?>)" href="#">Edit</a></td>
                                                  <td><a onclick="deleteItem('ind', <?=$indicator->id?>, <?=$idBusinessLine?>, <?=$idOutcome?>, <?=$idOutput?>)" href="#">Delete</a></td>
                                                </tr>
											                     <?php }
                                            } else { echo 'No information'; }?>
                                            </tbody>
                                        </table>
                                    </div> <!-- FIN Tabla con el contenido de Business Lines -->
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" class="footer">
                                	<input onclick="showNewItemModal('in', <?=$idOutput?>, 0)" value="Add Indicator" type="button" class="footer_button" />
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td class="separadorMenu" colspan="3">
                        <table class="contenedora" cellpadding="0" cellspacing="0">
                            <tr>
                                <td class="descripcion">Indicator Owner</td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="scroll-pane-arrows"> <!-- Tabla con el contenido de Indicator Owner -->
                                        <table width="100%" id="tblOwnerIndicator" class="tablaJerarquia">
                                            <tbody>
											                     <?php if($idIndicator != 0) {
                                            	if (count($users) > 0) { 
                    													foreach($users as $user) { ?>
                                              <tr <?php if($user->id == $idOwner) echo "class='row_selected'";?>>
                                                <td class="tdDescripcion">
                    																<?php echo $user->firstName . ' ' . $user->lastName; ?></td>
                                                <td>
                                                <?php if($user->id != $idOwner && $changeOwner) { ?>
                                                <a href="<?php
                    																$url = 'indicator/setOwner/' . $idIndicator . '/' . $user->id . '/' . $idBusinessLine . '/' . $idOutcome . '/' . $idOutput;
                    																echo site_url("$url"); ?>">Choose</a>
                                                <?php } else { echo '&nbsp;'; } ?>
                                                </td>
                                              </tr>
                                              <?php }
                                            	} else { echo 'No information'; }
											                      }?>
                                            </tbody>
                                        </table>
                                    </div> <!-- FIN Tabla con el contenido de Business Lines -->
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td class="footer">
            <input onclick="document.location.href='<?php echo site_url('information/downloadReport/' . $idBusinessLine); ?>'" value="Download Tree Structure" type="button" class="footer_button" />
        </td>            
    </tr>
</table>

<!-- FORMULARIOS POP-UP -->
<div class='modal-form' id="warning_modal"> 
    <span id='warning_msg'></span>
</div>

<div class='modal-form' id="add_b_line">
</div>

<div class='modal-form' id="add_outcome">
</div>

<div class='modal-form' id="add_output"> 
</div>

<div class='modal-form' id="add_indicator"> 
</div>